package com.hoshiicloud.user.controller.usercenter;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.user.controller.BaseController;
import com.hoshiicloud.user.entity.usercenter.MemberAccount;
import com.hoshiicloud.user.param.usercenter.MemberAccountPageParam;
import com.hoshiicloud.user.param.usercenter.MemberAccountUpdateParam;
import com.hoshiicloud.user.service.usercenter.IMemberAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户账户Controller类
 *
 * @author : yangcheng
 * @date : 2019/5/11 09:40
 * @mail : maiboyc@163.com
 **/
@RestController
@RequestMapping("/memberAccount")
@Api(value = "用户账户信息管理", tags = {"用户账户信息操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class MemberAccountController extends BaseController {

    // 用户账户Service
    @Autowired
    private IMemberAccountService memberAccountService;

    /**
     * 根据ID查询用户账户信息
     * @param id 用户ID
     * @return Response
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询", notes = "根据ID查询用户账户信息", consumes = MediaType.ALL_VALUE)
    public Response<MemberAccount> get(@PathVariable("id") Long id) {
        Response<MemberAccount> rs;
        try {
            rs = Response.data(memberAccountService.getById(id));
        } catch (Exception e) {
            logger.error("根据ID查询用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID组查询用户账户信息
     * @param ids 用户ID组
     * @return Response
     */
    @GetMapping("/getByIds")
    @ApiOperation(value = "根据ID组查询", notes = "根据ID组查询用户账户信息", consumes = MediaType.ALL_VALUE)
    public Response<List<MemberAccount>> get(@RequestParam("ids") List<Long> ids) {
        Response<List<MemberAccount>> rs;
        try {
            rs = Response.data(memberAccountService.getByIds(ids));
        } catch (Exception e) {
            logger.error("根据ID组查询用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据用户ID查询用户账户信息
     * @param userId  用户ID
     * @return Response
     */
    @GetMapping("/find/{userId}")
    @ApiOperation(value = "根据名称查询", notes = "根据名称查询用户账户信息", consumes = MediaType.ALL_VALUE)
    public Response<IPage<MemberAccount>> findByName(@PathVariable("userId") Long userId) {
        Response<IPage<MemberAccount>> rs;
        try {
            MemberAccount entity = new MemberAccount();
            entity.setUserId(userId);
            rs = Response.data(memberAccountService.List(entity));
        } catch (Exception e) {
            logger.error("根据用户ID查询用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询用户账户信息（get请求，以具体值接收参数）
     * @param pageIndex     当前页码
     * @param pageSize      每页显示的记录数
     * @param userId        用户ID
     * @param settlement    结算方式
     * @return Response
     */
    @GetMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询用户账户信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "当前页码", required = true, dataType = "Long", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "Long", example = "10", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "Long", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "settlement", value = "结算方式", dataType = "Integer", example = "1", paramType = "query")
    })
    public Response<IPage<MemberAccount>> list(Long pageIndex, Long pageSize, Long userId, Integer settlement) {
        Response<IPage<MemberAccount>> rs;
        try {
            MemberAccount entity = new MemberAccount();
            entity.setPageIndex(pageIndex);
            entity.setPageSize(pageSize);
            entity.setUserId(userId);
            entity.setSettlement(settlement);
            rs = Response.data(memberAccountService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询用户账户信息（post请求，以对象接收参数）
     * @param param 查询参数实体
     * @return Response
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询用户账户信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<IPage<MemberAccount>> list(@RequestBody MemberAccountPageParam param) {
        Response<IPage<MemberAccount>> rs;
        try {
            MemberAccount entity = new MemberAccount();
            BeanUtils.copyProperties(param, entity);
            rs = Response.data(memberAccountService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 新增用户账户信息
     * @param entity 保存参数实体
     * @return Response
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增用户账户信息", notes = "新增用户账户信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> save(@RequestBody @Valid MemberAccount entity, BindingResult result) {
        Response<Long> rs;
        try {
            if (CollectionUtils.isNotEmpty(handleValidMsg(result))){// 验证不通过
                rs = Response.failed(objectMapper.writeValueAsString(handleValidMsg(result)));
            } else {// 验证通过
                rs = Response.data(memberAccountService.insert(entity));
            }
        } catch (JsonProcessingException e) {
            logger.error("处理JSON验证信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        } catch (ServiceException e) {
            logger.error("新增用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        }catch (Exception e) {
            logger.error("新增用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 修改用户账户信息
     * @param param 修改参数实体
     * @return Response
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改用户账户信息", notes = "修改用户账户信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> updateById(@RequestBody @Valid MemberAccountUpdateParam param, BindingResult result) {
        Response<Long> rs;
        try {
            if (CollectionUtils.isNotEmpty(handleValidMsg(result))){// 验证不通过
                rs = Response.failed(objectMapper.writeValueAsString(handleValidMsg(result)));
            } else {// 验证通过
                MemberAccount entity = new MemberAccount();
                BeanUtils.copyProperties(param, entity);
                rs = Response.data(memberAccountService.update(entity));
            }
        } catch (JsonProcessingException e) {
            logger.error("处理JSON验证信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        } catch (ServiceException e) {
            logger.error("更新用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("更新用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID删除用户账户信息
     * @param id 用户ID
     * @return Response
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除用户账户信息", consumes = MediaType.ALL_VALUE)
    public Response<Boolean> deleteById(@PathVariable("id") Long id) {
        Response<Boolean> rs;
        try {
            rs = Response.data(memberAccountService.delete(id));
        } catch (ServiceException e) {
            logger.error("删除用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("删除用户账户信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }
    
}  